package com.ping.study.utils.tx;

import com.ping.study.model.dto.tx.LiveInfoRequest;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.DayOfWeek;
import java.time.Instant;

@Component
public class CKeyGenerator {

    public String generateCKey(String cnlid, String platform) {
        // 获取当前时间戳(秒级)
        String tm = String.valueOf(Instant.now().getEpochSecond());

        // 获取当天星期几和密钥
        DayOfWeek today = DayOfWeek.from(java.time.LocalDate.now());
        String secretKey = LiveInfoRequest.getTodaySecretKey();
        String encryptVer = LiveInfoRequest.generateEncryptVer(today);

        // 构建输入字符串
        String input = secretKey + cnlid + tm + "*#06#" + platform;

        try {
            // 计算MD5
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));

            // 转换为16进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }

            return hexString.toString();
        } catch (Exception e) {
            throw new RuntimeException("生成ckey失败", e);
        }
    }
}